/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-15
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-15
 * @Description: 
 */

import 'package:chat_client/config/api_config.dart';
import 'package:chat_client/enums/chat_enum.dart';
import 'package:chat_client/models/contact_model.dart';
import 'package:chat_client/models/group_model.dart';
import 'package:chat_client/models/session_model.dart';
import 'package:chat_client/models/user_model.dart';
import 'package:chat_client/screens/chat/chat_page.dart';
import 'package:chat_client/services/group_service.dart';
import 'package:chat_client/services/user_service.dart';
import 'package:chat_client/utils/show_messae.dart';
import 'package:chat_client/widgets/c_loading.dart';
import 'package:chat_client/widgets/c_square_avatar.dart';
import 'package:flutter/material.dart';

import '../../../services/contact_service.dart';
import 'package:chat_client/router/router.dart';

class CreateGroupScreen extends StatefulWidget {
  const CreateGroupScreen({super.key});

  @override
  State<StatefulWidget> createState() {
    return _CreateGroupScreenState();
  }
}

class _CreateGroupScreenState extends State<CreateGroupScreen> {
  final ContactService _contactService = ContactService.instance;
  final GroupService _groupService = GroupService.instance;
  final UserService _userService = UserService.instance;

  final TextEditingController _textController = TextEditingController();

  List<Contact> _contactList = [];

  Map<int, bool> member = {};

  _createGroup() async {
    Loading.show(message: '正在创建群聊');
    try {
      final User user = _userService.getLocalUserInfo();
      // 提取值为 true 的键
      List<int> selectedIndex = member.entries
          .where((entry) => entry.value == true)
          .map((entry) => entry.key)
          .toList();
      final List<String> contactIds = [];
      String groupName = user.nickname;
      for (var i in selectedIndex) {
        contactIds.add(_contactList[i].userId);

        if (groupName.length > 20) continue;
        groupName += ',${_contactList[i].nickname}';
      }

      // 创建
      final Group? group = await _groupService.createGroup(
          contactIds: contactIds, groupName: groupName);
      if (group != null) {
        popMessage('群聊创建成功');

        /// 转跳到群聊会话
        final SessionModel session = SessionModel(
          id: group.groupId,
          type: ConversationType.group.value,
          name: group.groupName,
        );
        RouteManager.navigateToWidget(ChatScreen(session: session));
      }
    } catch (e) {
      popError(e.toString(), '群聊创建失败');
    } finally {
      Loading.hide();
    }
  }

  _check(int index) {
    setState(() {
      if (member[index] == null) {
        member.putIfAbsent(index, () => true);
      }
      member[index] = member[index] == false ? true : false;
    });
  }

  @override
  void initState() {
    _contactList = _contactService.getLocalContactList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('新的朋友')),
        body: Column(
          children: [
            Container(
              color: Colors.transparent,
              padding:
                  EdgeInsets.only(right: 20, left: 20, top: 10, bottom: 20),
              child: TextField(
                decoration: InputDecoration(prefixIcon: Icon(Icons.search)),
                controller: _textController,
              ),
            ),
            _buildCationList()
          ],
        ),
        persistentFooterButtons: [
          ElevatedButton(
              onPressed: () {
                _createGroup();
              },
              child: Text('完成'))
        ]);
  }

  Widget _buildCationList() {
    return Expanded(
      child: ListView.separated(
        physics: BouncingScrollPhysics(),
        itemCount: _contactList.length,
        itemBuilder: (context, index) {
          return _bildListItem(_contactList[index], index);
        },
        separatorBuilder: (context, index) => Divider(height: 1),
      ),
    );
  }

  _bildListItem(Contact contact, int index) {
    return Material(
      // Material 组件提供触摸反馈的上下文
      color: Colors.white,
      child: InkWell(
        // 控制水波纹颜色和形状
        splashColor: Colors.grey.withValues(alpha: 0.2),
        borderRadius: BorderRadius.circular(8),
        onTap: () {
          _check(index);
        },
        child: Padding(
          // 通过 Padding 模拟 ListTile 的内边距
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          child: Row(
            children: [
              Container(
                  padding: EdgeInsets.only(right: 10),
                  child: Transform.scale(
                    scale: 1.5,
                    child: Checkbox(
                      value: member[index] ?? false,
                      onChanged: (value) {
                        _check(index);
                      },
                    ),
                  )),
              SquareAvatar(
                imageSource: AppConfig.baseUrl + contact.avatarUrl,
                size: 54,
                borderRadius: 10,
              ),
              SizedBox(width: 20),
              Text(
                contact.nickname,
                style: TextStyle(
                  fontSize: 20,
                  color: Colors.grey[800],
                  fontWeight: FontWeight.w600,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
